package cn.taketoday.live.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.taketoday.live.config.GlobalData;
import cn.taketoday.live.data.Weather;
import cn.taketoday.live.data.heart.XData;
import cn.taketoday.live.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author BanqiJane
 */
@Slf4j
public class HttpOtherData {

  public static Long httpGetClockInRecord() {
    String data = null;
    JSONObject jsonObject = null;
    Long uid = null;
    String code = "-1";
    Map<String, String> headers = null;
    Map<String, String> datas = null;
    headers = new HashMap<>(2);
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    datas = new HashMap<>(4);
    datas.put("uid", GlobalData.USER.getUid().toString());
    datas.put("edition", GlobalData.EDITION);
    datas.put("time", String.valueOf(System.currentTimeMillis()));
    try {
      data = HttpUtils.get("http://bilibili.acproject.xyz/getClockRecord", headers, datas)
              .body().string();
    }
    catch (Exception e) {
      // TODO 自动生成的 catch 块
      log.error("httpGetClockInRecord", e);
      uid = null;
      log.error("请求服务器超时，获取最新打卡记录失败");
      data = null;
    }
    if (data == null)
      return null;
    jsonObject = JSONObject.parseObject(data);
    code = jsonObject.getString("code");
    if (code.equals("200")) {
      if (jsonObject.get("result") != null) {
        uid = ((JSONObject) jsonObject.get("result")).getLong("uid");
      }
    }
    else {
      log.error("未知错误,原因:" + jsonObject.getString("msg"));
    }
    return uid;
  }

  public static Long httpPOSTSetClockInRecord() {
    String data = null;
    JSONObject jsonObject = null;
    Long uid = null;
    String code = "-1";
    Map<String, String> headers = null;
    Map<String, String> datas = null;
    headers = new HashMap<>(2);
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    datas = new HashMap<>(4);
    datas.put("uid", GlobalData.USER.getUid().toString());
    datas.put("edition", GlobalData.EDITION);
    datas.put("time", String.valueOf(System.currentTimeMillis()));
    try {
      data = HttpUtils
              .post("http://bilibili.acproject.xyz/setClockRecord", headers, datas)
              .body().string();
    }
    catch (Exception e) {
      // TODO 自动生成的 catch 块
      log.error("httpPOSTSetClockInRecord", e);
      uid = null;
      log.error("请求服务器超时，获取最新打卡记录失败");
      data = null;
    }
    if (data == null)
      return null;
    jsonObject = JSONObject.parseObject(data);
    code = jsonObject.getString("code");
    if (code.equals("200")) {
      if (jsonObject.get("result") != null) {
        uid = ((JSONObject) jsonObject.get("result")).getLong("uid");
      }
    }
    else {
      log.error("未知错误,原因:" + jsonObject.getString("msg"));
    }
    return uid;
  }

  public static String httpGetIp() {
    String data = null;
    JSONObject jsonObject = null;
    String status = null;
    String ip = null;
    Map<String, String> headers = null;
    headers = new HashMap<>(2);
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    try {
      data = HttpUtils.getString("http://ip-api.com/json/", headers, null);
    }
    catch (Exception e) {
      log.error("httpGetIp", e);
      data = null;
    }
    if (data == null)
      return null;
    jsonObject = JSONObject.parseObject(data);
    try {
      status = jsonObject.getString("status");
    }
    catch (Exception e) {
      // TODO: handle exception
    }
    if (StringUtils.isEmpty(status)) {
      return "获取失败:请自行获取本机对公Ip地址";
    }
    if (status.equals("success")) {
      ip = jsonObject.getString("query");
    }
    else {
      log.error("获取ip失败" + jsonObject.toString());
    }
    return ip;
  }

  public static String httpPostEncsUrl() {
    String data = null;
    JSONObject jsonObject = null;
    String url = null;
    String code = "-1";
    Map<String, String> headers = null;
    Map<String, String> datas = null;
    headers = new HashMap<>(2);
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    datas = new HashMap<>(4);
    datas.put("roomid", GlobalData.centerSetConf.getRoomid().toString());
    datas.put("edition", GlobalData.EDITION);
    datas.put("time", String.valueOf(System.currentTimeMillis()));
    try {
      data = HttpUtils
              .post("http://bilibili.acproject.xyz/getEncsServer", headers, datas)
              .body().string();
    }
    catch (Exception e) {
      // TODO 自动生成的 catch 块
      log.error("httpPostEncsUrl", e);
      url = null;
      log.error("请求服务器超时，获取服务器链接失败");
      data = null;
    }
    if (data == null)
      return url;
    jsonObject = JSONObject.parseObject(data);
    code = jsonObject.getString("code");
    if (code.equals("200")) {
      url = jsonObject.getString("result");
      GlobalData.SMALLHEART_ADRESS = url;
    }
    else {
      log.error("未知错误,原因: {}", jsonObject.getString("msg"));
    }
    return url;
  }

  /**
   * 加密s函数方法来自 https://github.com/lkeme/bilibili-pcheartbeat
   * 服务器来自 https://github.com/lkeme/BiliHelper-personal
   *
   * @param xData
   * @param ts
   *
   * @return
   */
  public static String httpPostencS(XData xData, long ts) {
    String data = null;
    JSONObject jsonObject = null;
    String s = null;
    String url = GlobalData.SMALLHEART_ADRESS;
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    Map<String, String> headers = null;
    headers = new HashMap<>(2);
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    JSONObject t = new JSONObject();
    t.put("id", xData.getId());
    t.put("device", xData.getDevice());
    t.put("ets", xData.getEts());
    t.put("benchmark", xData.getBenchmark());
    t.put("time", xData.getTime());
    t.put("ts", ts);
    t.put("ua", xData.getUa());
    JSONObject json = new JSONObject();
    json.put("t", t);
    json.put("r", xData.getSecret_rule());
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    try {
      data = HttpUtils.postString(url, headers, json.toJSONString());
    }
    catch (Exception e) {
      // TODO 自动生成的 catch 块
      log.error("连接至加密服务器错误？不存在");
      data = null;
//			e.printStackTrace();
    }
    if (data == null)
      return null;
    jsonObject = JSONObject.parseObject(data);
    try {
      s = jsonObject.getString("s");
    }
    catch (Exception e) {
      log.error("加密s错误");
      // TODO: handle exception
      s = null;
    }
    return s;
  }

  public static Weather httpPostWeather(String city, Short day) {
    String data = null;
    JSONObject jsonObject = null;
    String code = "-1";
    Weather weather = null;
    Map<String, String> headers = null;
    Map<String, String> datas = null;
    headers = new HashMap<>(2);
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    datas = new HashMap<>(3);
    datas.put("city", city);
    datas.put("day", day.toString());
    try {
      data = HttpUtils
              .post("http://bilibili.acproject.xyz/getWeather", headers, datas)
              .body().string();
    }
    catch (Exception e) {
      // TODO 自动生成的 catch 块
      log.error("httpPostWeather", e);
      log.error("请求服务器超时，获取服务器链接失败");
      data = null;
    }
    if (data == null)
      return null;
    jsonObject = JSONObject.parseObject(data);
    code = jsonObject.getString("code");
    if (code.equals("200")) {
      weather = JSONObject.parseObject(jsonObject.getString("result"), Weather.class);
    }
    else {
      log.error("未知错误,原因:" + jsonObject.getString("msg"));
    }
    return weather;
  }
  // 天气接口http://wthrcdn.etouch.cn/weather_mini?city=北京  备用

  public static Map<String, List<Weather>> httpGetweather(String city) {
    String data = null;
    JSONObject jsonObject = null;
    short code = -1;
    Map<String, String> headers = null;
    headers = new HashMap<>(2);
    Map<String, List<Weather>> weathers = null;
    String cname = null;
    String ganmao = null;
    String wendu = null;
    headers.put("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
    try {
      data = HttpUtils
              .get("http://wthrcdn.etouch.cn/weather_mini?city=" + city, headers, null)
              .body().string();
    }
    catch (Exception e) {
      // TODO 自动生成的 catch 块
      log.error("httpGetweather", e);
      log.error("请求服务器超时，获取天气失败");
      data = null;
    }
    if (data == null)
      return null;
    try {
      jsonObject = JSONObject.parseObject(data);
      code = jsonObject.getShort("status");
      if (code == 1000) {
        weathers = new HashMap<String, List<Weather>>();
        cname = ((JSONObject) jsonObject.get("data")).getString("city");
        ganmao = ((JSONObject) jsonObject.get("data")).getString("ganmao");
        wendu = ((JSONObject) jsonObject.get("data")).getString("wendu");
        List<Weather> oldWeathers = new ArrayList<>();
        Weather oldWeather = JSONObject.parseObject(((JSONObject) jsonObject.get("data")).getString("yesterday"), Weather.class);
        oldWeather.setCity(cname);
        oldWeather.setGanmao(ganmao);
        oldWeather.setWendu(wendu);
        oldWeathers.add(oldWeather);
        weathers.put("old", oldWeathers);
        List<Weather> newWeathers = JSONArray.parseArray(((JSONObject) jsonObject.get("data")).getString("forecast"), Weather.class);
        weathers.put("new", newWeathers);
        for (Iterator<Weather> iterator = newWeathers.iterator(); iterator.hasNext(); ) {
          Weather weather = iterator.next();
          weather.setWendu(wendu);
          weather.setGanmao(ganmao);
          weather.setCity(cname);
        }
      }
      else {
        log.error("未知错误,原因:" + jsonObject.getString("desc"));
      }
    }
    catch (Exception e) {
      weathers = null;
    }
    return weathers;
  }
}
